import datetime
from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import FlashPayUser
from .core import FlashPayCore

UserModel = get_user_model()
flash_pay_core = FlashPayCore()


class FlashLogin(serializers.Serializer):
    code = serializers.CharField(required=True, allow_blank=False, allow_null=False)

    def save(self, **kwargs):
        code = self.validated_data.get("code")
        flash_user_info = flash_pay_core.get_access_token(code)
        openid = flash_user_info.get("openId")
        union_id = flash_user_info.get("unionId")
        access_token = flash_user_info.get("accessToken")
        expires_in = flash_user_info.get("expiresIn")
        mobile = flash_pay_core.get_user_mobile(openid, access_token)
        FlashPayUser.objects.update_or_create(
            openid=openid,
            defaults={'union_id': union_id, "access_token": access_token,
                      "expires_in": datetime.datetime.now() + datetime.timedelta(seconds=expires_in - 60),
                      "mobile": mobile}
        )
        if UserModel.objects.filter(mobile=mobile).exists():
            pass
        else:
            # 创建新用户 注意是否新用户需要赠券
            pass
